package com.dg11185.nearshop.activity.user;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.nearshop.R;
import com.dg11185.libs.imageloader.core.DisplayImageOptions;
import com.dg11185.libs.imageloader.core.ImageLoader;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.network.http.client.HttpRequest.ActionListener;
import com.dg11185.libs.utils.file.FileUtils;
import com.dg11185.nearshop.activity.BaseFragment;
import com.dg11185.nearshop.activity.user.info.UserInfoActivity;
import com.dg11185.nearshop.activity.user.order.ActivityRecordActivity;
import com.dg11185.nearshop.activity.user.order.LotteryRecordActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.MyApplication;
import com.dg11185.nearshop.app.StaticData;
import com.dg11185.nearshop.app.Utils;
import com.dg11185.nearshop.net.CacheConstant;
import com.dg11185.nearshop.net.request.GetCardListRequest;
import com.dg11185.nearshop.net.request.LoginRequest;
import com.dg11185.nearshop.net.request.ModifyHeadPhotoRequest;
import com.dg11185.nearshop.net.request.UploadUserIcon;
import com.dg11185.nearshop.net.request.UploadUserIcon.UploadUserIconResponse;
import com.dg11185.nearshop.net.response.GetCardListResponse;
import com.dg11185.nearshop.net.response.GetCardListResponse.Card;
import com.dg11185.nearshop.net.response.LoginResponse;
import com.dg11185.nearshop.net.response.ModifyInfoResponse;
import com.google.zxing.client.CaptureActivity;
import com.umeng.analytics.MobclickAgent;
import com.wlper.lib.uitls.LogUtils;
import com.wlper.lib.uitls.StringUtils;
import com.wlper.lib.uitls.ViewUtils;

/**
 * 个人中心
 * 
 * @author wanliang527
 * @date 2014-5-15
 */
public class UserFragment extends BaseFragment {

    private final static String DGTLMK = "东莞通联名卡";

    public static final String IMAGE_PATH = "/Nearshop/img/temp/";

    public final static int LOGIN_ACTY = 1; // 登录requestCode
    public final static int USER_INFO_ACTY = 2;// 用户资料requestCode
    public final static int ACTIVATION_ACTY = 3;// 激活requestCode
    public final static int BIND_ACTY = 4;// 绑定requestCode
    private final static int SYS_ALBUM_ACTIVITY = 5;// 手机相册requestCode
    private final static int SYS_CAMERA_ACTIVITY = 6;// 手机相机requestCode
    private final static int MODIFY_PIC_ACTIVITY = 7;// 裁剪图片requestCode
    private final static int UPLOAD_SUCCESS = 21;
    private final static int UPLOAD_FAILED = 22;
    private final static int NET_ERROR = 23;
    private DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheInMemory().showStubImage(R.drawable.icon_user_icon_bg)
            .build();

    // 标题栏中间区域，用于添加标题
    private LinearLayout tMidLayout;

    private View loginView, notLoginView;
    // 已登录界面的相关控件
    private TextView mUserNameT;// 用户名
    private ImageView mUserIconI;// 用户头像
    private Button goForMoreB;// 个人详细资料
    // 未登录界面的相关控件
    private Button goLoginB;// 登录按钮

    private Button goActivateB;// 激活
    private Button scanB;// 扫描按钮
    private ViewGroup mCardEntry;// 常惠卡
    private ListView mListView;
    private Dialog mdPhotoDialog;// 修改头像对话框

    private LoginResponse mLoginRes;
    private GetCardListResponse mGetCardRes;

    /**
     * 用来标识常惠卡列表是否需要更新，激活或者绑定成功后返回用户中心，需要将此标识设置为true
     * 调用onGetCardList并成功返回数据后，将此标识设为false
     */
    private boolean cardListUpdated;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    HashMap<String, Object> data1 = (HashMap<String, Object>) msg.obj;
                    Bitmap photo = (Bitmap) data1.get("photoBp");
                    String minPhoto = (String) data1.get("imgUrl");
                    mLoginRes.minPhoto = minPhoto;
                    modiFyUserIcon(photo, minPhoto);
                    break;

                case UPLOAD_FAILED:
                    HashMap<String, Object> data2 = (HashMap<String, Object>) msg.obj;
                    String status = (String) data2.get("status");
                    hideLoading();
                    ViewUtils.showToast(mActivity, "上传头像失败");
                    LogUtils.logNetError("上传头像失败___" + status);
                    break;

                case NET_ERROR:
                    int resultCode = (Integer) msg.obj;
                    hideLoading();
                    ViewUtils
                            .showToast(mActivity, "上传头像失败\n网络错误：" + resultCode);
                    LogUtils.logNetError("上传头像失败___" + resultCode);
                    break;
            }
            super.handleMessage(msg);
        }

    };

    /**
     * 点击事件
     */

    private OnClickListener mClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            // 电子常惠卡
                case R.id.view_m_card:
                    if (isNotLogin())
                        return;
                    onGetCardList();
                    break;
                // 扫描按钮
                case R.id.btn_scan:
                    if (isNotLogin())
                        return;
                    startActivity(new Intent(mActivity, CaptureActivity.class));
                    break;
                // 更换头像
                case R.id.image_v_user_icon:
                    getMdPhotoDialog().show();
                    break;
                // 激活
                case R.id.btn_activate:
                    if (isNotLogin())
                        return;
                    goActivate();
                    break;

                // 点击去更多资料
                case R.id.btn_go_more_user_info:
                case R.id.view_login:
                    Intent goMoreUserInfo = new Intent(mActivity,
                            UserInfoActivity.class);
                    if (!StringUtils.isStrNull(mLoginRes.userId))
                        goMoreUserInfo.putExtra(Constants.USER_ID, mLoginRes);
                    goMoreUserInfo.putExtra(Constants.LOGIN_NAME,
                            getLoginName());
                    startActivityForResult(goMoreUserInfo, USER_INFO_ACTY);
                    break;
                // 点击去登录
                case R.id.btn_go_login:
                    Intent goLogin = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(goLogin, LOGIN_ACTY);
                    break;
                // 拍照按钮的点击事件
                case R.id.btn_take_photo:
                    hideMdPhotoDialog();
                    modifyByTakePhoto();
                    break;
                // 从相册选择的点击事件
                case R.id.btn_select_from_album:
                    hideMdPhotoDialog();
                    modifyFromAlbum();
                    break;
                // 取消的点击事件
                case R.id.btn_cancel:
                    hideMdPhotoDialog();
                    break;
            }
        }
    };

    /**
     * 列表点击事件
     */

    private OnItemClickListener mItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            if (isNotLogin())
                return;
            TextView txt = (TextView) view.findViewById(R.id.txt_v_item_name);
            if (txt.getText().equals("最近浏览商家")) {
                Intent intent = new Intent(mActivity,
                        BrowseRecordActivity.class);
                startActivity(intent);
                return;
            }

            if (txt.getText().equals("我的关注商家")) {
                Intent intent = new Intent(mActivity,
                        FavoriteShopActivity.class);
                startActivity(intent);
                return;
            }
            if (txt.getText().equals("我的抽奖")) {
                Intent intent = new Intent(mActivity,
                        LotteryRecordActivity.class);
                startActivity(intent);
                return;
            }
            ViewUtils.showToast(mActivity, "功能暂未开放，敬请期待");
        }
    };

    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return createView(inflater);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getName());
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getName());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        // 从登录界面返回，更新UI
            case LOGIN_ACTY:
                if (resultCode == Activity.RESULT_OK) {
                    mLoginRes = (LoginResponse) data
                            .getSerializableExtra("loginRes");
                    updateLoginView();
                }
                break;

            // 从个人中心界面返回，更新UI
            case USER_INFO_ACTY:
                // 如果用户已经注销，就删除登录数据
                if (resultCode == UserInfoActivity.LOGOUT) {
                    FileUtils.deleteDirectory(CacheConstant.getCachePath());
                    loginView.setVisibility(View.GONE);
                    notLoginView.setVisibility(View.VISIBLE);
                    clearUserInfo();
                }
                break;

            case ACTIVATION_ACTY:
                if (resultCode == Activity.RESULT_OK)
                    cardListUpdated = true;
                break;

            case BIND_ACTY:
                if (resultCode == Activity.RESULT_OK)
                    cardListUpdated = true;
                break;

            // 从系统相册返回
            case SYS_ALBUM_ACTIVITY:
                if (data == null)
                    return;
                startPhotoZoom(data.getData());
                break;

            // 从照相机返回
            case SYS_CAMERA_ACTIVITY:
                if (resultCode == Activity.RESULT_OK) {
                    File file = new File(
                            Environment.getExternalStorageDirectory()
                                    + IMAGE_PATH, mLoginRes.userId + ".jpg");
                    startPhotoZoom(Uri.fromFile(file));
                }

                break;

            // 从修改图片的Activity中返回
            case MODIFY_PIC_ACTIVITY:
                if (data == null)
                    return;
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    if (photo != null)
                        uploadPhoto(photo);
                }
                break;
        }
    }

    /**
     * 创建界面视图
     * 
     * @param inflater
     * @return
     */
    private View createView(LayoutInflater inflater) {
        if (mInflater == null)
            mInflater = inflater;
        View view = mInflater.inflate(R.layout.fragment_user, null);
        // 实例化控件对象
        findViews(view);
        // 添加标题
        TextView titleView = new TextView(mActivity);
        titleView.setTextColor(getResources().getColor(R.color.white));
        titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                Constants.TITLE_FONT_SIZE);
        titleView.setGravity(Gravity.CENTER);
        titleView.setText("个人中心");
        tMidLayout.addView(titleView,ViewUtils.WRAP_MATCH);
        if (MyApplication.getUser() != null) {
            // 如果在别处已经登录了，就直接使用已有的登录数据
            mLoginRes = MyApplication.getUser();
            updateLoginView();
        } else {
            // 否则，根据用户偏好设定来决定是否要进行自动登录
            if (mPreferences.getBoolean(Constants.ISAUTOLOGIN, false)) {
                if (mPreferences.contains(Constants.ACCTOUNT)
                        && mPreferences.contains(Constants.PASSWORD)) {
                    showLoading();
                    LoginRequest req = new LoginRequest(mPreferences.getString(
                            Constants.ACCTOUNT, ""), mPreferences.getString(
                            Constants.PASSWORD, ""));
                    req.setActionListener(new ActionListener<LoginResponse>() {
                        @Override
                        public void onSuccess(LoginResponse result) {
                            LogUtils.logNetReturn(Constants.login,
                                    result.responseStr);
                            hideLoading();
                            if (!result.status.equals(LoginResponse.SUCCESS)) {
                                ViewUtils.showToast(mActivity, "自动登录失败，请手动登录！");
                                return;
                            }
                            mLoginRes = result;
                            MyApplication.setUser(mLoginRes);
                            updateLoginView();
                        }

                        @Override
                        public void onFailure(int resultCode) {
                            hideLoading();
                            ViewUtils.showToast(mActivity, "自动登录失败，请手动登录！");
                        }
                    });
                    NetClient.httpPost(req);
                }
            }
        }
        loginView.setOnClickListener(mClickListener);
        mUserIconI.setOnClickListener(mClickListener);
        goForMoreB.setOnClickListener(mClickListener);
        goLoginB.setOnClickListener(mClickListener);
        goActivateB.setOnClickListener(mClickListener);
        scanB.setOnClickListener(mClickListener);
        mCardEntry.setOnClickListener(mClickListener);
        mListView.setAdapter(new SimpleAdapter(mActivity, StaticData
                .getUserItemData(mActivity), R.layout.view_user_record_item,
                new String[] { "itemIcon", "itemName", "itemSize" }, new int[] {
                        R.id.image_icon, R.id.txt_v_item_name,
                        R.id.txt_v_record_counts }));
        mListView.setOnItemClickListener(mItemClickListener);

        return view;
    }

    /**
     * 实例化控件
     */
    private void findViews(View view) {
        tMidLayout = (LinearLayout) view.findViewById(R.id.llayout_middle);
        loginView = view.findViewById(R.id.view_login);
        notLoginView = view.findViewById(R.id.view_not_login);
        mUserNameT = (TextView) view.findViewById(R.id.txt_v_user_name);
        mUserIconI = (ImageView) view.findViewById(R.id.image_v_user_icon);
        goForMoreB = (Button) view.findViewById(R.id.btn_go_more_user_info);
        goLoginB = (Button) view.findViewById(R.id.btn_go_login);
        goActivateB = (Button) view.findViewById(R.id.btn_activate);
        scanB = (Button) view.findViewById(R.id.btn_scan);
        mCardEntry = (ViewGroup) view.findViewById(R.id.view_m_card);
        mListView = (ListView) view.findViewById(R.id.list_v);
    }

    /**
     * 更新已登录界面的相关信息，例如头像、用户名等，更新之前隐藏未登录界面，显示已登录界面
     */
    private void updateLoginView() {
        if (mLoginRes == null)
            return;
        notLoginView.setVisibility(View.GONE);
        loginView.setVisibility(View.VISIBLE);
        if (!StringUtils.isStrNull(mLoginRes.minPhoto)) {
            ImageLoader.getInstance().displayImage(mLoginRes.minPhoto,
                    mUserIconI, options);
        } else {
            ImageLoader.getInstance().displayImage("null", mUserIconI, options);
        }
        if (!StringUtils.isStrNull(mLoginRes.userName)) {
            mUserNameT.setText(mLoginRes.userName);
        } else if (!StringUtils.isStrNull(mLoginRes.mobilePhone)) {
            mUserNameT.setText(mLoginRes.mobilePhone);
        } else if (!StringUtils.isStrNull(mLoginRes.email)) {
            mUserNameT.setText(mLoginRes.email);
        }
    }

    /**
     * 联网获取我的常惠卡
     */
    private void onGetCardList() {
        if (!cardListUpdated && mGetCardRes != null) {
            onGetCardListRes();
            return;
        }
        String loginName = getLoginName();
        showLoading();
        GetCardListRequest req = new GetCardListRequest(loginName);
        req.setActionListener(new ActionListener<GetCardListResponse>() {

            @Override
            public void onSuccess(GetCardListResponse result) {
                hideLoading();
                LogUtils.logNetReturn(Constants.getList, result.responseStr);
                String status = result.status;
                if (status.equals(GetCardListResponse.SUCCESS)) {
                    mGetCardRes = result;
                    cardListUpdated = false;
                    onGetCardListRes();
                } else {
                    LogUtils.logNetError("获取常惠卡列表失败---" + result.status);
                    ViewUtils.showToast(mActivity, R.string.network_error);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                hideLoading();
                LogUtils.logNetError("获取常惠卡列表失败---" + resultCode);
                if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                    ViewUtils.showToast(mActivity,
                            R.string.cant_connect_network);
                } else {
                    ViewUtils.showToast(mActivity, R.string.network_error);
                }
            }
        });
        NetClient.httpPost(req);
    }

    /**
     * 处理常惠卡列表的返回数据
     */
    private void onGetCardListRes() {
        if (mGetCardRes == null)
            return;
        if (mGetCardRes.cardList == null || mGetCardRes.cardList.size() == 0) {
            goActivate();
        } else {
            View cardView = mInflater.inflate(R.layout.view_e_card, null);
            LinearLayout cardList = (LinearLayout) cardView
                    .findViewById(R.id.llayout_e_card_list);
            for (int i = 0; i < mGetCardRes.cardList.size(); i++) {
                View v = createCardView(mGetCardRes.cardList.get(i));
                LayoutParams params = new LayoutParams(
                        (int) (mScreenWidth * 0.9),
                        (int) (mScreenWidth * 0.9 * 0.75));
                cardList.addView(v, params);
                ((LinearLayout.LayoutParams) v.getLayoutParams()).bottomMargin = 20;
            }
            Dialog eCard = new Dialog(mActivity, R.style.e_card_show);
            eCard.setContentView(cardView);
            eCard.show();
        }
    }

    /**
     * 创建一张电子常惠卡
     * 
     * @param data
     * @return
     */
    private View createCardView(Card data) {
        View view = mInflater.inflate(R.layout.view_single_e_card, null);
        Button cardNo = (Button) view.findViewById(R.id.view_e_card_no);
        cardNo.setText(data.cardFaceNo);
        if (data.cardDesc.equals(DGTLMK)) {
            cardNo.setBackgroundResource(R.drawable.pic_e_card_3_1);
        }
        TextView validity = (TextView) view.findViewById(R.id.txt_v_validity);
        validity.setText("有效时间：" + data.endTime);
        TextView todayDate = (TextView) view
                .findViewById(R.id.txt_v_today_date);
        TextView typeDesc = (TextView) view.findViewById(R.id.txt_v_card_desc);
        typeDesc.setText(data.cardDesc);
        todayDate.setText("当前时间："
                + Utils.getTime(new SimpleDateFormat("yyyy-MM-dd")));
        return view;
    }

    /**
     * 上传头像。
     * 
     * @param photo
     */
    private void uploadPhoto(final Bitmap photo) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);

        if (Utils.saveBitmap2File(photo,
                Environment.getExternalStorageDirectory() + IMAGE_PATH,
                mLoginRes.userId + "_crop.jpg")) {
            String fileAbsPath = Environment.getExternalStorageDirectory()
                    + IMAGE_PATH + mLoginRes.userId + "_crop.jpg";
            File imgFile = new File(fileAbsPath);
            UploadUserIcon req = new UploadUserIcon(imgFile, mLoginRes.userId);
            showLoading();
            req.setUploadResponse(new UploadUserIconResponse() {
                Message msg = new Message();
                HashMap<String, Object> data = new HashMap<String, Object>();

                @Override
                public void onSuccess(String responseStr, String status,
                        String minPhoto) {
                    data.put("photoBp", photo);
                    data.put("status", status);
                    data.put("imgUrl", minPhoto);
                    msg.obj = data;
                    if (status.equals("SUCCESS")) {
                        msg.what = UPLOAD_SUCCESS;
                        mHandler.sendMessage(msg);
                    } else {
                        msg.what = UPLOAD_FAILED;
                        mHandler.sendMessage(msg);
                    }
                }

                @Override
                public void onFailed(int resultCode) {
                    msg.obj = resultCode;
                    msg.what = NET_ERROR;
                    mHandler.sendMessage(msg);
                }
            });
            req.upload();
        }
    }

    /**
     * 修改头像。在上传头像成功之后调用
     * 
     * @param photo
     * @param imageUrl
     */
    private void modiFyUserIcon(final Bitmap photo, String imageUrl) {
        if (photo == null || StringUtils.isStrNull(imageUrl))
            return;
        ModifyHeadPhotoRequest req = new ModifyHeadPhotoRequest(getLoginName(),
                imageUrl);
        req.setActionListener(new ActionListener<ModifyInfoResponse>() {
            @Override
            public void onSuccess(ModifyInfoResponse result) {
                Log.i("test", Constants.modifyHeadPhoto + "\n"
                        + result.responseStr);
                if (result.status.equals(ModifyInfoResponse.SUCCESS)) {
                    hideLoading();
                    mUserIconI.setImageBitmap(photo);
                    ViewUtils.showToast(mActivity, "修改头像成功");
                } else {
                    ViewUtils.showToast(mActivity, "修改头像失败_" + result.status);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                hideLoading();
                ViewUtils.showToast(mActivity, "修改头像失败\n网络错误：" + resultCode);
            }
        });
        NetClient.httpPost(req);
    }

    /**
     * 图片处理
     * 
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 128);
        intent.putExtra("outputY", 128);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, MODIFY_PIC_ACTIVITY);
    }

    /**
     * 获取修改头像对话框
     * 
     * @return
     */
    private Dialog getMdPhotoDialog() {
        if (mdPhotoDialog == null) {
            View mdyPhoto = mInflater.inflate(R.layout.view_modify_user_icon,
                    null);
            mdyPhoto.findViewById(R.id.btn_take_photo).setOnClickListener(
                    mClickListener);
            mdyPhoto.findViewById(R.id.btn_select_from_album)
                    .setOnClickListener(mClickListener);
            mdyPhoto.findViewById(R.id.btn_cancel).setOnClickListener(
                    mClickListener);
            mdPhotoDialog = new Dialog(mActivity, R.style.loading_dialog);
            mdPhotoDialog.setContentView(mdyPhoto, new LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            Window dialogWindow = mdPhotoDialog.getWindow();
            dialogWindow.setGravity(Gravity.BOTTOM);
            dialogWindow.setWindowAnimations(R.style.BottomDialog);
            WindowManager.LayoutParams lP = dialogWindow.getAttributes();
            lP.width = (int) mActivity.getWindowManager().getDefaultDisplay()
                    .getWidth();
        }
        return mdPhotoDialog;
    }

    /**
     * 隐藏修改头像对话框
     */
    private void hideMdPhotoDialog() {
        if (mdPhotoDialog != null || mdPhotoDialog.isShowing())
            mdPhotoDialog.dismiss();
    }

    /**
     * 打开系统相册
     */
    private void modifyFromAlbum() {

        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, SYS_ALBUM_ACTIVITY);
    }

    /**
     * 打开系统相机
     */
    private void modifyByTakePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        File path = new File(Environment.getExternalStorageDirectory()
                + IMAGE_PATH);
        path.mkdirs();
        File file = new File(Environment.getExternalStorageDirectory()
                + IMAGE_PATH, mLoginRes.userId + ".jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(intent, SYS_CAMERA_ACTIVITY);
    }

    /**
     * 检测是否已登录，未登录的话直接跳到登录界面。
     */
    private boolean isNotLogin() {
        if (mLoginRes == null) {
            startActivityForResult(new Intent(mActivity, LoginActivity.class),
                    LOGIN_ACTY);
            return true;
        }
        return false;
    }

    /**
     * 根据登录的返回数据，获取登录名。优先获取用户名，其次是手机号、邮箱。
     * 
     * @return
     */
    public String getLoginName() {
        if (mLoginRes == null)
            return "";
        if (StringUtils.isStrNull(mLoginRes.userName)) {
            if (StringUtils.isStrNull(mLoginRes.mobilePhone)) {
                return mLoginRes.email;
            } else {
                return mLoginRes.mobilePhone;
            }
        } else {
            return mLoginRes.userName;
        }
    }

    /**
     * 启动激活界面
     */
    private void goActivate() {
        Intent goActivate = new Intent(mActivity, ActivationActivity.class);
        if (!StringUtils.isStrNull(mLoginRes.mobilePhone)) {
            goActivate.putExtra("mobilePhone", mLoginRes.mobilePhone);
        }
        goActivate.putExtra("loginName", getLoginName());
        startActivityForResult(goActivate, ACTIVATION_ACTY);
    }

    /**
     * 清空用户数据，用于注销时调用
     */
    private void clearUserInfo() {
        mLoginRes = null;
        mGetCardRes = null;
        Editor editor = mPreferences.edit();
        editor.remove(Constants.ISAUTOLOGIN);
        editor.remove(Constants.REMPASSWD);
        editor.remove(Constants.ACCTOUNT);
        editor.remove(Constants.PASSWORD);
        editor.commit();
    }

    @Override
    public View setContentView() {
        return null;
    }

    @Override
    public boolean initTopBanner() {
        return false;
    }
}
